package com.sec.etech.employeesync.confighandler;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.sec.etech.employeesync.entity.OrgEmployeeZEthnicity;
import com.sec.etech.employeesync.mapper.OrgEmployeeZEthnicityMapper;
import com.sec.etech.employeesync.util.ConfigTableHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Optional;

@Component
@Slf4j
public class EthnicityConfigHandler implements ConfigTableHandler<OrgEmployeeZEthnicity> {

    @Resource
    private OrgEmployeeZEthnicityMapper ethnicityMapper;

    @Override
    public Long getOrCreateConfigId(String... params) {
        String name = params[0];
        OrgEmployeeZEthnicity ethnicity = getEntityByName(name);
        if (ethnicity == null) {
            ethnicity = new OrgEmployeeZEthnicity();
            ethnicity.setCode(generateNextCode());
            ethnicity.setName(name);
            ethnicity.setActive(1);
            insertEntity(ethnicity);
            log.info("新增民族配置:name={}", name);
        }
        return ethnicity.getEthnicityId();
    }

    @Override
    public OrgEmployeeZEthnicity getEntityByName(String name) {
        return ethnicityMapper.selectOne(Wrappers.<OrgEmployeeZEthnicity>lambdaQuery()
                .eq(OrgEmployeeZEthnicity::getName, name));
    }

    @Override
    public String generateNextCode() {
        OrgEmployeeZEthnicity orgEmployeeZEthnicity = ethnicityMapper.selectOne(Wrappers.<OrgEmployeeZEthnicity>lambdaQuery()
                .orderByDesc(OrgEmployeeZEthnicity::getCode)
                .last("limit 1"));

        String lastCode = Optional.ofNullable(orgEmployeeZEthnicity)
                .map(OrgEmployeeZEthnicity::getCode)
                .orElse("0");

        return generateNextCode(lastCode);
    }

    @Override
    public void insertEntity(OrgEmployeeZEthnicity entity) {
        ethnicityMapper.insert(entity);
    }
}
